
import Utils from "./utils/Utils";
import LableChange from "./utils/LableChange";
import EffectUtils from "./utils/EffectUtils";
import GameData, { languageData, NumData } from './GameData';
import { PlayableSDK, PlayableType } from './sdk/PlayableSDK';
import Anim from './utils/Anim';
import UsdPrefab from './UsdPrefab';
import NumItem from "./NumItem";
import BallItem from "./BallItem";
import EventManager from "./core/EventManager";
import { LanguageComponent } from "./language/LanguageComponent";
import { LanguageManager } from "./language/LanguageManager";
import MoneyChange from "./utils/MoneyChange";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GameUI extends cc.Component {
    @property(cc.Node)
    private ballBg:cc.Node = null
    @property(cc.Node)
    private bgNode:cc.Node = null
    @property(cc.Node)
    private verCoin:cc.Node = null
    @property(cc.Node)
    private horCoin:cc.Node = null
    @property(cc.Node)
    public portraitCon: cc.Node = null;
    @property(cc.Label)
    public moneyTxt1: cc.Label = null;
    @property(cc.Node)
    public middleCon: cc.Node = null;
    @property(cc.Node)
    public mainCon: cc.Node = null;
    @property(cc.Node)
    public resultUI: cc.Node = null;
    @property(cc.Label)
    public r_winTxt: cc.Label = null;
    @property(cc.Node)
    public landscapeConTip: cc.Node = null;
    @property(cc.Node)
    public landscapeCon: cc.Node = null;
    @property(cc.Label)
    public moneyTxt2: cc.Label = null;
    @property(cc.Prefab)
    public usdPrefab: cc.Prefab = null;
    @property(cc.Node)
    public hand: cc.Node = null
    @property(cc.Node)
    public hintNode: cc.Node = null;
    @property(cc.Node)
    public hintNode1: cc.Node = null;

    @property(cc.Node)
    public usdNode: cc.Node = null;

    @property(cc.Node)
    public ballCon: cc.Node = null;
    @property(cc.Node)
    public boxNode: cc.Node = null;

    @property(cc.Prefab)
    public ballPrefab: cc.Prefab = null;


    //声音
    @property({ type: cc.AudioClip })
    public clickAudioClip: cc.AudioClip = null;
    @property({ type: cc.AudioClip })
    public blockRemove: cc.AudioClip = null;
    @property({ type: cc.AudioClip })
    public winAudioClip: cc.AudioClip = null;
    @property({ type: cc.AudioClip })
    public addCoin: cc.AudioClip = null;

    @property(cc.Prefab)
    public moneyPrefab: cc.Prefab = null;
    @property([cc.SpriteFrame])
    public usdIconS0: cc.SpriteFrame[] = [];
    @property([cc.SpriteFrame])
    public usdIconS1: cc.SpriteFrame[] = [];
    private FloatingMoneyArr: cc.Node[];

    /**美元金额 */
    public usdCount: number = 100;
    /**游戏状态 */
    public gameState: boolean;
    /**动态文本 */
    public lableChange1: MoneyChange;
    public lableChange2: MoneyChange;
    /**当前次数 */
    public curIndex: number = 0;

    /**是否第一次点击 */
    private isFirstClick: boolean;

    public isReady: boolean = false;//是否可以开始
    private clickTime:number = 0

    /**地图上的 */
    private NumNodeArr: cc.Node[][];
    /**出球数据 */
    public ballArray: NumData[];
    /**球 */
    public ballList: cc.Node[] = [];
    /**出现的数字 */
    public nowNumArr: number[] = [];

    start() {
        GameData.languageInit();//语言初始化
        // PlayableSDK.adapter();
        // PlayableSDK.gameReady();
        // cc.game.setFrameRate(30);
        PlayerAdSdk.init()

        let that = this;
        /**屏幕旋转尺寸改变 */
        cc.view.setResizeCallback(() => {
            that.resize();
        })

        cc.find('Canvas').on("sizeChange", function (event) {
            that.resize();
        })

        cc.find('Canvas').on('touchstart', this.startClick, this);

        this.gameState = true;
        this.usdCount = LanguageManager.instance.formatUnit(this.usdCount)
        let unit = LanguageManager.instance.getText(10001)
        this.lableChange1 = new MoneyChange(this.moneyTxt1,false,this.usdCount);
        this.lableChange2 = new MoneyChange(this.moneyTxt2,false,this.usdCount);
        // this.lableChange1.prefix = unit
        this.moneyTxt1.string  = `${this.usdCount}`
        // this.lableChange2.prefix = unit
        this.moneyTxt2.string = `${this.usdCount}`

        this.initMapData();
        this.isReady = true;
        this.resize();
        this.setView();

        this.ballArray = Utils.copyDataHandler(GameData.ballArray);
        this.ballArray.sort((a, b) => {
            return Math.random() > 0.5 ? 1 : -1;
        })

        EventManager.on("createBall", this.createBall, this)
        this.createBall();


    }

    /**设置次数 */
    // public setBallsleft() {
    //     this.Ballsleft.string = `Ballsleft ${this.ballArray.length}`;
    // }




    /**初始化地图数据 */
    private initMapData() {
        let farme: cc.Node = this.mainCon;
        this.NumNodeArr = Utils.arrTrans(5, farme.children);

        let len1: number = this.mainCon.children.length;
        for (let i: number = 0; i < len1; i++) {
            let data: NumData = GameData.mapData[i];
            let node: cc.Node = this.mainCon.children[i];
            if (!node) continue;
            // node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this)
            node.on(cc.Node.EventType.TOUCH_END, this.clickMap, this)
            let numItem: NumItem = node.getComponent(NumItem);
            if (numItem) {
                numItem.data = data;
            }
        }
    }

    /**循环遍历 */
    private blockForEach(fun: Function) {
        let len1: number = this.NumNodeArr.length;
        let len2: number;
        for (let i: number = 0; i < len1; i++) {
            len2 = this.NumNodeArr[i].length;
            for (let j: number = 0; j < len2; j++) {
                fun.call(this, this.NumNodeArr[i][j], i, j)
            }
        }
    }

    private clickMap(e: cc.Event.EventTouch) {
        this.startClick();
        if (!this.gameState) return;
        let target: cc.Node = e.target;
        let numItem: NumItem = target.getComponent(NumItem);
        if (!numItem.state && this.numShow(numItem.num)) {//是否出现过
            cc.audioEngine.play(this.clickAudioClip, false, 1);
            this.clearGuild();
            numItem.state = 1;//选中
            this.ballList[0].getComponent(BallItem).stop();
            EventManager.emit("createBall")//出现新球
            /**判断bigon */
            if(this.clickTime < 4){
                this.isBingo();
                this.clickTime++
            }
            
        }
    }


    //创建球
    private createBall() {
        let len: number = this.ballArray.length;
        if (len <= 0) {//结束
            this.over();
        }
        let data: NumData;
        let index: number = Math.floor(Math.random() * this.ballArray.length);
        if (this.curIndex == 0) {//第一个默认66
            index = GameData.findIndex(this.ballArray, 66);
        }
        data = this.ballArray.splice(index, 1)[0];
        if (!data) return;
        let ball = cc.instantiate(this.ballPrefab);
        ball.parent = this.ballCon;
        ball.x = ball.y = 0;
        ball.scale = 1.4;
        let ballItem: BallItem = ball.getComponent(BallItem);
        ballItem.data = data;
        if (this.curIndex > 0) {//第一次不前进，只有点击了才前进
            if (this.curIndex == GameData.ballArray.length - 1) {//最后一个时间常点
                ballItem.play(GameData.ballTime * 2);
            } else {
                ballItem.play(GameData.ballTime);
            }
        }
        if (this.ballList.length >= 5) {
            let node = this.ballList.pop();
            node.destroy();
        }
        this.ballList.unshift(ball);
        this.moveBall();
        // this.setBallsleft();
        this.setGuild();
        this.nowNumArr.push(data.num);
        //数字动效
        let node: cc.Node = this.getNowNum();
        let numItem: NumItem = node.getComponent(NumItem);
        numItem.hint();
        this.curIndex++;
    }
    /**移动球 */
    private moveBall() {
        let len: number = this.ballList.length;
        for (let i: number = 0; i < len; i++) {
            let node: cc.Node = this.ballList[i];
            if (i == 0) {
                node.scale = 0;
                node.x = 0;
                cc.tween(node).delay(0.1).to(0.2, { scale: 1.4 }).start();
            } else {
                node.scale = 1;
                if (this.ballCon.x == 265) {
                    cc.tween(node).to(0.3, { x: -170 - 120 * (i - 1) }).start();
                } else {
                    cc.tween(node).to(0.3, { y: -200 - 130 * (i - 1) }).start();
                }

            }
        }
    }

    /**显示随机宝箱 */
    public showBox() {
        let arr: cc.Node[] = [];
        let len1: number = this.mainCon.children.length;
        for (let i: number = 0; i < len1; i++) {
            let data: NumData = GameData.mapData[i];
            let node: cc.Node = this.mainCon.children[i];
            if (!node) continue;
            let numItem: NumItem = node.getComponent(NumItem);
            if (numItem.state == 0) {
                arr.push(node)
            }
        }
        let node: cc.Node = arr[Utils.limitInteger(0, arr.length)];
        this.boxNode.active = true;
        let point = Utils.getLocalPositionWithOtherNode(this.middleCon, node);
        this.boxNode.position = point;
        EffectUtils.zhuandong(this.boxNode, 0.2)
    }




    /**设置面板 */
    private setView() {
        let payType = GameData.payType;
        let topPay: cc.Sprite = this.portraitCon.getChildByName("topCon").getChildByName("box").getComponent(cc.Sprite);
        Utils.loadSpeite(`common/paypal0_${payType}`, topPay)
        let moneyLabel1: cc.Node = this.portraitCon.getChildByName("topCon").getChildByName("moneyTxt1");
        if (payType == 1) {
            moneyLabel1.color = new cc.Color(1, 33, 105, 255);
        } else {
            moneyLabel1.color = new cc.Color(196, 130, 2, 255);
        }
    }

    /**设置提示信息 */
    private setHint() {
        let str: string = "Practice Game Only";//mtg没翻译 
        let PractiveLabel: cc.Node = this.hintNode.getChildByName("PractiveLabel");
        let hint: cc.Label = PractiveLabel.getComponent(cc.Label);
        let rectWhite: cc.Node = this.hintNode.getChildByName("rectWhite");
        let PractiveLabel1: cc.Node = this.hintNode1.getChildByName("PractiveLabel");
        let hint1: cc.Label = PractiveLabel1.getComponent(cc.Label);
        let rectWhite1: cc.Node = this.hintNode1.getChildByName("rectWhite");

        if (window["SDKTYPE"] == PlayableType.Mindworks) {//mtg默认都是英文 
            str = "Result is not guaranteed. Amount paid to you is subject to rules in the app.";

            rectWhite.width = 520;
            rectWhite.height = 80;
            hint1.fontSize = 30;
            PractiveLabel.width = 500;

            rectWhite1.width = 730;
            rectWhite1.height = 110;
            hint1.fontSize = 40;
            PractiveLabel1.width = 700;

        } else {
            rectWhite.width = 320;
            rectWhite.height = 50;
            hint1.fontSize = 30;

            rectWhite1.width = 550;
            rectWhite1.height = 100;
            hint1.fontSize = 50;
            PractiveLabel1.width = 500;
        }
        hint.string = str;
        hint1.string = str;


    }
    private startClick() {
        /**点击播放音乐 */
        if (!this.isFirstClick) {
            this.isFirstClick = true;
            let audioSource: cc.AudioSource = this.node.getComponent(cc.AudioSource);
            if (audioSource) {
                audioSource.play();
            }
        }
    }
    /**
     * isBingo
     */
    public isBingo() {
        let result = GameData.isBingo(this.mainCon.children);
        let len: number = result.length;
        if (len > 0) {
            result.forEach((node: cc.Node, index: number) => {
                let num: NumItem = node.getComponent(NumItem);
                cc.tween(node).delay(0.08 * index).call(() => {
                    num.state = 2;
                }, this).to(0.1, { scale: 1.1 }).to(0.1, { scale: 1 }).start();
            }, this)

            this.usdChange();
        }
    }

    /**美元更新 */
    private async usdChange() {
        let target: cc.Node;
        if (cc.winSize.height > cc.winSize.width) {//竖屏
            target = this.portraitCon.getChildByName("topCon").getChildByName("moneyTxt1");
        } else {
            target = this.landscapeCon.getChildByName("card").getChildByName("moneyTxt2");
        }
        let point = Utils.getLocalPositionWithOtherNode(this.node, target);
        /**飞美元 */
        Anim.ins().ShowFlyAni(this.usdPrefab, this.node, 30, point, () => {
            EffectUtils.removeTweens(target);

        }, this)
        await Utils.await(600);
        EffectUtils.startScale(target, 0.2, 1, 0.2);

        /******************这里加金币 *************************/
        this.usdCount += LanguageManager.instance.formatUnit(GameData.addUsdCount);


        this.lableChange1.play(this.usdCount, 1)
        this.lableChange2.play(this.usdCount, 1)
    }




    /**点击下载 */
    public downClick(event, customEventData) {
        cc.audioEngine.play(this.clickAudioClip, false, 1)
        console.log('跳转');
        PlayerAdSdk.gameEnd()
        PlayerAdSdk.jumpStore()
    }
    private cashoutFunc() {
        console.log('跳转');
        // this.canPlayMusic && cc.audioEngine.play(RESSpriteFrame.instance.clickAudioClip, false, 1)
        PlayerAdSdk.gameEnd()
        PlayerAdSdk.jumpStore()
    }



    /*是否结束*/
    private async over() {
        this.showBox();
        if (this.gameState) {
            this.gameState = false;
            await Utils.await(2000);
            Utils.SetScale(this.moneyTxt1.node,1.15,0.2,false,1)
            Utils.SetScale(this.moneyTxt2.node,1.15,0.2,false,1)
            this.moneyTxt1.string = `${LanguageManager.instance.formatUnit(300)}`
            this.moneyTxt2.string = `${LanguageManager.instance.formatUnit(300)}`
            this.resultUI.active = true;
            let endStr: string = ".00";
            if (this.usdCount >= 1000) {
                endStr = "";
            }
            // this.r_moneyTxt.string = `$${this.usdCount}${endStr}`;
            // this.r_winTxt.string = `YOU WIN $${this.usdCount}${endStr}`;
            let cashOutBtn: cc.Node = this.resultUI.getChildByName("cashOutBtn")
            EffectUtils.startScale(cashOutBtn, 0.2)
            this.setGuild();
            /**全屏点击 */
            let canvas = cc.find('Canvas');
            canvas.on('touchstart', this.downClick, this);
            cc.audioEngine.play(this.winAudioClip, false, 1)
            PlayableSDK.gameEnd();
            this.FloatingMoney();
            return;
        }
    }



    /**飘钱 */
    private FloatingMoney() {
        this.FloatingMoneyArr = [];
        let _W: number = 2560;
        let _H: number = 1334;
        let iconArr;
        if (GameData.gameType == 0) {
            iconArr = this.usdIconS0;
        } else if (GameData.gameType == 1) {
            iconArr = this.usdIconS1;
        }
        for (let r: number = 0; r < iconArr.length; r++) {
            this.scheduleOnce(function () {
                for (var i = 0; i <= 25; i++) {
                    var x = Math.random();
                    x = Utils.limit((-_W / 2) * 0.95, (_W / 2) * 0.95)
                    var y = Utils.limit(_H / 2 + 200, _H / 2 + 600);
                    var xVel = Math.random();
                    xVel = xVel > 0.5 ? -xVel * 4 : xVel * 8;
                    var yVel = -Math.random() * 5;
                    var xscale = Utils.limit(0.4, 0.72);
                    var particle = cc.instantiate(this.moneyPrefab) as cc.Node;
                    particle.parent = this.usdNode;
                    let sp: UsdPrefab = particle.addComponent(UsdPrefab);
                    let spriteFrame = iconArr[Math.floor(Math.random() * iconArr.length)];
                    sp.initData(x, y, xVel, yVel, xscale, spriteFrame);
                    this.FloatingMoneyArr.push(particle);
                }
            }, r * 1);

        }

    }




    /**指引 */
    public setGuild() {
        this.hand.stopAllActions();
        let point;
        if (!this.gameState) {
            let target: cc.Node = this.resultUI.getChildByName("cashOutBtn")
            point = Utils.getLocalPositionWithOtherNode(this.node, target);
        }

        let node: cc.Node = this.getNowNum();
        if (node) {
            point = Utils.getLocalPositionWithOtherNode(this.node, node);
        }
        if (point) {
            this.hand.active = true;
            this.hand.x = point.x + 15;
            this.hand.y = point.y - 15;
            cc.tween(this.hand).repeatForever(cc.tween().to(0.2, { scale: 1.1 }).to(0.2, { scale: 1 })).start();
        }
    }


    /**获取出现的数字 */
    public getNowNum() {
        let node: cc.Node = this.ballList[0];
        if (!node) return;
        let ball: BallItem = node.getComponent(BallItem);
        let len: number = this.mainCon.children.length;
        for (let i: number = 0; i < len; i++) {
            let data: NumData = GameData.mapData[i];
            let node: cc.Node = this.mainCon.children[i];
            if (!node) continue;
            let numItem: NumItem = node.getComponent(NumItem);
            if (numItem && numItem.num == ball.num && !numItem.data.state) {
                return node;
            }
        }
    }


    /**数字是否出现过 */
    public numShow(num: number) {
        let len: number = this.nowNumArr.length;
        for (let i: number = 0; i < len; i++) {
            if (this.nowNumArr[i] == num) {
                return true;
            }
        }
        return false;
    }

    /**设置球 */
    private setBall() {
        let len: number = this.ballList.length;
        for (let i: number = 0; i < len; i++) {
            let node: cc.Node = this.ballList[i];
            node.stopAllActions();
            if (i > 0) {
                node.scale = 1;
                if (this.ballCon.x == 265) {
                    node.x = -170 - 120 * (i - 1);
                    node.y = 0;
                } else {
                    node.x = 0;
                    node.y = -200 - 130 * (i - 1);
                }
            }
        }
    }

    /**清除指引 */
    public clearGuild() {
        this.hand.active = false;
        this.hand.stopAllActions();
    }

    /**
     * 重新设置布局
     */
    private resize() {
        const canvasValue: any = cc.Canvas.instance;
        let frameSize = cc.view.getFrameSize();
        let isVertical = cc.winSize.height > cc.winSize.width
        this.verCoin.active = isVertical
        this.horCoin.active = !isVertical
        this.bgNode.active = isVertical
        this.ballBg.active = isVertical
        if (cc.winSize.height > cc.winSize.width) {//竖屏
            if (cc.winSize.width / cc.winSize.height > 0.7) {
                cc.Canvas.instance.fitHeight = true;
                cc.Canvas.instance.fitWidth = false;
            } else {
                cc.Canvas.instance.fitHeight = false;
                cc.Canvas.instance.fitWidth = true;
            }
        } else {
            cc.Canvas.instance.fitHeight = true;  
            cc.Canvas.instance.fitWidth = false;
        }

        cc.director.getScene().getComponentsInChildren(cc.Widget).forEach(function (t) {
            t.updateAlignment()
        });

        /**适配 */
        if (cc.winSize.height > cc.winSize.width) {//竖屏
            this.portraitCon.active = true;
            this.landscapeCon.active = false;
            this.landscapeConTip.active = false;
            this.middleCon.scale = 1;
            this.middleCon.x = 0;
            this.middleCon.y = -180;

            this.resultUI.scale = 1;
            this.hand.width = 108;
            this.hand.height = 112;

            this.ballCon.x = 265;
            this.ballCon.y = 450;
        } else {
            this.portraitCon.active = false;
            this.landscapeCon.active = true;
            this.landscapeConTip.active = true;

            this.hand.width = 108 * 1.5;
            this.hand.height = 112 * 1.5;


            let scale: number = (this.node.height / this.middleCon.height);
            if (cc.winSize.height / cc.winSize.width > 0.74) {
                if (scale > 1.4) scale = 1.4;
            }
            if (scale > 1.7) scale = 1.7;
            this.middleCon.scaleX = this.middleCon.scaleY = scale;
            let mapW: number = this.middleCon.width * this.middleCon.scaleX;
            let mapH: number = this.middleCon.height * this.middleCon.scaleX;
            //金钱
            let leftW: number = this.node.width - mapW - 40;
            if (leftW > 900) leftW = 900;
            if (cc.winSize.width / 2 > 1280) {
                leftW = 1100;
            }
            this.landscapeCon.width = leftW;
            let scale1: number = this.landscapeCon.width / 1000;
            let con: cc.Node = this.landscapeCon.getChildByName("con");
            if (scale1 < 1) {
                con.scale = scale1;
            } else {
                con.scale = 1;
            }
            this.middleCon.y = 0;
            // this.middleCon.x = this.node.width / 2 - mapW / 2 - 30;
            this.middleCon.x = (this.node.width / 2) / 2;
            if (scale > 1.4) {//ipad特殊
                this.ballCon.x = -420;
                this.ballCon.y = 300;
                this.ballCon.scale = 0.8;
            } else if (scale == 1.4) {
                this.ballCon.scale = 0.7;
                this.middleCon.y = -80;
                this.middleCon.x = (this.node.width / 2) / 2 - 20;
            }
            console.log(scale, this.ballCon.x)
            this.resultUI.scale = 1.5;
        }
        this.setBall();
        this.setGuild();
        this.setHint();
    }

}
